import XLSX from "xlsx";
import VXETable from "vxe-table";

export default {
    cachePrefix: 'sblog.backend.',
    getCache(name, def = null) {
        let data = localStorage.getItem(this.cachePrefix + name);
        if (!data) return def;
        data = JSON.parse(data);
        //if (data.type === 'object') {}
        return data.value;
    },
    setCache(name, value) {
        let type = typeof (value);
        localStorage.setItem(this.cachePrefix + name, JSON.stringify({
            type,
            value,
        }));
    },
    clearCache() {
        let name = '';
        let names = [];
        for (let i = 0; i < localStorage.length; i++) {
            name = localStorage.key(i);
            if (name && name.indexOf(this.cachePrefix) > -1) names.push(name);
        }
        names.map(n => {
            localStorage.removeItem(n);
        });
    },
    // 转为实体
    escapeHTML: function (a) {
        a = "" + a;
        return a.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
    },
    // 转为HTML
    unescapeHTML: function (a) {
        a = "" + a;
        return a.replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&").replace(/&quot;/g, '"').replace(/&apos;/g, "'");
    },
    // 生成csv, 替代table2Excel, 速度更快
    table2Csv(titleLabel, jsonData, fileName = 'Excel') {
        //先转化json
        let arrData = typeof jsonData != 'object' ? JSON.parse(jsonData) : jsonData;
        //生成表头
        let str = titleLabel.join(',') + '\n';
        //循环生成表身
        for (let i = 0; i < arrData.length; i++) {
            str += arrData[i].join(',') + '\n';
        }
        this.downloadFile(str, fileName + ".csv");
    },
    // 将 string 转换成 blob 后下载文件
    downloadFile(blobContent, filename) {
        if (typeof blobContent === 'string') {
            var blob = new Blob([blobContent], {type: "text/plain;charset=utf-8"});
            blobContent = new Blob([String.fromCharCode(0xFEFF), blob], {type: blob.type});
        }
        let object_url = window.URL.createObjectURL(blobContent);
        var link = document.createElement("a");
        link.href = object_url;
        link.download = filename;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    },
    momentFromDateTime(dateTime) {
        return moment(dateTime, 'YYYY-MM-DD HH:mm:ss');
    },
    dateTimeToTimestamp(dateTime) {
        return this.momentFromDateTime(dateTime).unix();
    },
    timestampToDateTime(time) {
        return moment.unix(time).format("YYYY-MM-DD HH:mm:ss");
    },
    isMobile() {
        return navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i)
    },
    isJson(str) {
        if (typeof str === 'string') {
            try {
                var obj = JSON.parse(str);
                return typeof obj == 'object' && obj;
            } catch (e) {
                console.log('error：' + str + '!!!' + e);
                return false;
            }
        }
        return false;
    },
    randomStr(len = 32) {
        let baseStr = 'abcdefghijklmnopqrstuvwxyz1234567890',
            resStr = '';
        for (let i = 0; i < len; i++) {
            resStr += baseStr[Math.floor(Math.random() * 32)];
        }
        return resStr;
    },
    isIp(ip) {
        return new RegExp(/^(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d)\.(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d)\.(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d)\.(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d)$/).test(ip);
    },
    isIdcard(str) {
        const reg = /^(\d{14}|\d{17})(\d|x|X)$/;
        return reg.test(str);
    },
    isMobileNumber(str) {
        const reg = /^(\+?0?86\-?)?(1[3456789]{1}\d{9})$/;
        return reg.test(str)
    },
    clipboardCopy(text, event, callback) {
        const cb = new Clipboard('.t', {
            text: () => text
        });
        cb.on('success', (e) => {
            cb.off('error');
            cb.off('success');

            if (callback) callback(true);
        });
        cb.on('error', (e) => {
            cb.off('error');
            cb.off('success');
            console.error('clipboardCopy error', e);
            if (callback) callback(false);
        });
        cb.onClick(event);
    },
    /**
     * 在json数组中找到指定key等于value的第一项
     * @param  arr Array
     * @param key
     * @param value
     * @param d
     */
    findInJsonArray(arr, key, value, d) {
        let r = arr.filter(function (p) {
            return p[key] === value;
        });
        if (r.length === 0) {
            return d ? d : null
        } else {
            return r[0];
        }
    },
    // 深拷贝
    deepClone(obj) {
        let objClone = Array.isArray(obj) ? [] : {};
        if (obj && typeof obj === "object") {
            for (let key in obj) {
                if (obj.hasOwnProperty(key)) {
                    //判断ojb子元素是否为对象，如果是，递归复制
                    if (obj[key] && typeof obj[key] === "object") {
                        objClone[key] = this.deepClone(obj[key]);
                    } else {
                        //如果不是，简单复制
                        objClone[key] = obj[key];
                    }
                }
            }
        }
        return objClone;
    },
    isEmptyObj(obj) {
        return !obj || Object.keys(obj).length === 0;
    },
    // 数字格式化
    // numberFormat(num, split = 3) {
    //     num = num.toString().split('.')
    //     let arr = num[0].split('').reverse();
    //     let res = [];
    //     for (var i = 0; i < arr.length; i++) {
    //         if (i % split === 0 && i !== 0) {
    //             res.push(',');
    //         }
    //         res.push(arr[i]);
    //     }
    //     res.reverse();
    //     if (num[1]) {
    //         res = res.join('').concat('.' + num[1]);
    //     } else {
    //         res = res.join('');
    //     }
    //     return res;
    // },
    numberFormat(number, decimals, dec_point, thousands_sep) {
        if (decimals) {
            number = parseFloat(number).toFixed(decimals);   //转化为Float浮点型 并保留指定小数位
        }
        dec_point = dec_point ? dec_point : '.';
        thousands_sep = thousands_sep ? thousands_sep : ',';
        var source = String(number).split(".");
        source[0] = source[0].replace(new RegExp('(\\d)(?=(\\d{3})+$)', 'ig'), "$1" + thousands_sep);
        return source.join(dec_point);
    },
    // 转换成人民币
    numberRmb(num, toFixed = 2) {
        if (isNaN(num+0)) return 0;
        let res = parseFloat(num / 100);
        if (toFixed > 0) {
            res = Number(res.toFixed(toFixed));
        }
        return res;
    },
    numberFixed(num, toFixed = 2) {
        if (isNaN(parseFloat(num))) return 0;
        return parseFloat(num).toFixed(toFixed) || 0;
    },
    numberPercent(cellValue, prefix = '%', toFixed = 1) {
        if (isNaN(Number(cellValue))) return cellValue;
        if (!cellValue) return 0;
        cellValue = (cellValue * 100).toFixed(toFixed);
        return cellValue == 0 ? 0 : cellValue + prefix;
    },
    // 千分位数字
    formatHuman(cellValue, fixed = 0) {
        if (isNaN(Number(cellValue))) return cellValue;
        if (!cellValue) return 0;
        cellValue = fixed ? parseFloat(cellValue).toFixed(fixed) : Math.round(cellValue);
        return cellValue ? this.numberFormat(cellValue) : 0;
    },
    formatHumanRmb(cellValue, fixed = 0) {
        if (isNaN(Number(cellValue))) return cellValue;
        if (!cellValue) return 0;
        cellValue = fixed ? parseFloat(cellValue/100).toFixed(fixed) : Math.round(cellValue/100);
        return cellValue ? this.numberFormat(cellValue) : 0;
    },
    formatPercent(cellValue, fixed = 1) {
        if (isNaN(Number(cellValue))) return cellValue;
        if (!cellValue) return 0;
        cellValue = (cellValue * 100).toFixed(fixed);
        return cellValue == 0 ? 0 : cellValue + '%';
    },
    //定义导出Excel表格事件
    exportExcel(filename, selector = '#table') {
        let fix = document.querySelector(selector) ? document.querySelector(selector).querySelector('.el-table__fixed') : false;
        let wb
        if (fix) {
            wb = XLSX.utils.table_to_book(document.querySelector(selector).removeChild(fix), {raw: true})
            document.querySelector(selector).appendChild(fix)
        }else {
            wb = XLSX.utils.table_to_book(document.querySelector(selector), {raw: true})
        }
        let wbout = XLSX.write(wb, {
            bookType: "xlsx",
            bookSST: true,
            type: "array"
        });
        return this.downloadFile(
            new Blob([wbout], { type: "application/octet-stream" }),
            filename
        )
    },
    formatSeconds(value) {
        if (!value) return value;
        var secondTime = parseInt(value);// 秒
        var minuteTime = 0;// 分
        var hourTime = 0;// 小时
        if(secondTime > 60) {//如果秒数大于60，将秒数转换成整数
            //获取分钟，除以60取整数，得到整数分钟
            minuteTime = parseInt(secondTime / 60);
            //获取秒数，秒数取佘，得到整数秒数
            secondTime = parseInt(secondTime % 60);
            //如果分钟大于60，将分钟转换成小时
            if(minuteTime > 60) {
                //获取小时，获取分钟除以60，得到整数小时
                hourTime = parseInt(minuteTime / 60);
                //获取小时后取佘的分，获取分钟除以60取佘的分
                minuteTime = parseInt(minuteTime % 60);
            }
        }
        var result = "" + (secondTime < 10 ? "0"+secondTime : secondTime);

        if(minuteTime > 0) {
            result = "" + (minuteTime < 10 ? "0"+minuteTime : minuteTime) + ":" + result;
        } else {
            result = "00:" + result;
        }
        if(hourTime > 0) {
            result = "" + (hourTime < 10 ? "0"+hourTime : hourTime) + ":" + result;
        } else {
            result = "00:" + result;
        }
        return result;
    },
    // 除法
    calcDivision(a, b) {
        return b ? a/b : 0;
    },
    vxeFooter(columns, data, skipFunc, calcFunc) {
        let sums = [];
        let allFields = {};
        let fieldFormatterFuncs = {};
        let fieldFormatted = [];

        // 使用单元格指定的格式化方式
        let formatterFunc = (index, value) => {
            // 已经处理过
            if (fieldFormatted[index]) return value;

            let cellValue = {cellValue: value || 0,};
            let func = fieldFormatterFuncs[index];

            // 未设置的 || isNaN
            if (!func || isNaN(value)) return value;
            let params = [cellValue];

            // "formatterXXX", ["formatterXXX", 2, xxx]
            if (Array.isArray(func)) {
                params.push(func[1]);
                func = func[0];
            }
            fieldFormatted[index] = 1;
            return VXETable.formats.get(func)(...params);
        }

        columns.forEach((column, index) => {
            allFields[column.property] = index;
            fieldFormatterFuncs[index] = column.formatter;

            if (index === 0) {
                sums[index] = '汇总';
                return;
            }
            // 某些字段需要跳过
            if (skipFunc && typeof skipFunc === 'function') {
                if (skipFunc(index, column.property)) {
                    sums[index] = '-';
                    return ;
                }
            }

            let values = data.map(item => Number(item[column.property]));
            if (!values.every(value => isNaN(value))) {
                sums[index] = values.reduce((prev, curr) => {
                    const value = Number(curr);
                    if (!isNaN(value)) {
                        return prev + curr;
                    } else {
                        return prev;
                    }
                }, 0);

            } else {
                sums[index] = '';
            }
        });
        if (calcFunc && typeof calcFunc === 'function') {
            sums = calcFunc(sums, allFields);
        }
        Object.keys(allFields).map(field => {
            sums[allFields[field]] = formatterFunc(allFields[field], sums[allFields[field]]);
        });

        return [sums];
    },
    parseInt(val) {
        val = parseInt(val);
        return isNaN(val) ? 0 : val;
    },
    formatW(val, fixed = 0) {
        if (isNaN(Number(val))) return val;
        if (!val) return 0;
        val = fixed ? parseFloat(val/10000).toFixed(fixed) : Math.round(val/10000);
        return val>0 ? this.numberFormat(val)+'w' : 0;
    },
}
